package com.xxx.system.service.impl;


import com.github.pagehelper.PageHelper;
import com.xxx.system.domain.Employee;
import com.xxx.system.domain.Role;
import com.xxx.system.mapper.EmployeeMapper;
import com.xxx.system.query.EmployeeQuery;
import com.xxx.system.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// 查询事务控制方式：设置只读 支持当前事务，如果没有当前事务，就以非事务方法执行。
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void addEmployee(Employee employee) {
        employeeMapper.addEmployee(employee);

        //添加员工的同时,把员工的id(插入,通过sql配置uk)和角色id的集合插入到员工角色中间表
        if (employee.getRoleids().size()>0){
            employeeMapper.addEmpAndRoles(employee);//假设法
        }
    }

    @Override
    @Transactional
    public void updateEmployee(Employee employee) {
        employeeMapper.updateEmployee(employee);

        //修改(先删,再添加就是一种修改),维护中间表?如何维护?
        employeeMapper.delEmpAndRoles(employee.getId());

        if (employee.getRoleids().size()>0){
            employeeMapper.addEmpAndRoles(employee);//假设法
        }
    }

    @Override
    @Transactional
    public void deteleById(Long id) {
        employeeMapper.deteleById(id);

        employeeMapper.delEmpAndRoles(id);//删除中间表
    }

    @Override
    @Transactional
    public void deleteEmployeeByIds(Long[] ids) {
        employeeMapper.deleteEmployeeByIds(ids);

        employeeMapper.delEmpAndRoles2(ids);//批量删除中间表
    }

    @Override
    public Employee findOne(Long id) {
        return employeeMapper.findOne(id);
    }

    @Override
    public List<Employee> findAll() {
        return employeeMapper.findAll();
    }

    @Override
    public List<Employee> queryPage(EmployeeQuery employeeQuery) {
        //开始设置分页信息
        //干了三件事情：
        //1.查询总条数 2.根据驱动名称自动添加分页 3.分页查询返回结果
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        //直接高级查询，自动实现分页

        //每一个员工,id,关联这个角色集合,查sql查出来
        List<Employee> employees = employeeMapper.queryPage(employeeQuery);//ctr 1

        // for (Employee employee : employees) {
        //     List<Role> dbRoles=employeeMapper.findDbRoles(employee.getId());//假设法
        //     employee.setDbRoles(dbRoles);
        // }

        return employees;
    }
}
